package com.gao.controller;

import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;

/**
 * @author GuLe
 */
@Slf4j
@RestController
public class AuthController {
    @Autowired
    Producer producer;

    @Autowired
    JavaMailSender javaMailSender;

    /**
     * 获取验证码
     */
    @GetMapping("/captcha")
    public Object captcha(HttpSession session) throws IOException {
        String code = producer.createText();
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());
        log.info("code = " + code);
        session.setAttribute("code", code);
        return base64Img;
    }

    /**
     * 验证 并发送邮件
     */
    @PostMapping("/send")
    public Object sendEmail(HttpSession session, HttpServletResponse response, @RequestBody Map<String, String> data) throws IOException {
        String code = data.get("code");
        String title = data.get("title");
        String text = data.get("text");
        String thisCode = ((String) Optional.ofNullable(session.getAttribute("code")).orElse("-"));
        if (thisCode.equalsIgnoreCase(code)) {
            log.info("发送成功! data:" + data);
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("1244699029@qq.com");
            message.setTo("1244699029@qq.com");
            message.setSubject("来自网友" + title);
            message.setText(text);
            javaMailSender.send(message);
            session.removeAttribute("code");
        } else {
            log.info("发送失败! data:" + data);
            log.warn("验证码错误!");
            session.removeAttribute("code");
            response.sendError(400);
        }
        return "";
    }

}
